package com.zadtek.sharkRider.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.view.Window;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.AMapNaviViewListener;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.autonavi.tbt.TrafficFacilityInfo;
import com.zadtek.sharkRider.R;
import com.zadtek.sharkRider.util.AMapUtil;

public class MyMapLocation extends Activity implements AMapNaviListener, AMapNaviViewListener,AMapLocationListener {
	private String endlat;
	private String endlng;
//	AMapNaviView mAMapNaviView;
//    AMapNavi mAMapNavi;
//    TTSController mTtsManager;
//    NaviLatLng mEndLatlng = new NaviLatLng(0.0, 0.0);
//    NaviLatLng mStartLatlng = new NaviLatLng(0.0, 0.0);
//    List<NaviLatLng> mStartList = new ArrayList<NaviLatLng>();
//    List<NaviLatLng> mEndList = new ArrayList<NaviLatLng>();
//    List<NaviLatLng> mWayPointList;
    // 声明mLocationOption对象
		public AMapLocationClientOption mLocationOption = null;
		private AMapLocationClient mlocationClient;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_basic_navi);
		
		Bundle bundle =this.getIntent().getExtras();
		if (bundle  !=null) {
			endlat=bundle.getString("lat");
			endlng=bundle.getString("lng");
//			mEndLatlng.setLatitude(Double.parseDouble(endlat));
//			mEndLatlng.setLongitude(Double.parseDouble(endlng));
//			
//			mAMapNaviView = (AMapNaviView) findViewById(R.id.navi_view);
//			mAMapNaviView.onCreate(savedInstanceState);
//			mAMapNaviView.setAMapNaviViewListener(this);
		isAppInstalled(MyMapLocation.this, "com.autonavi.minimap");
			
//			  //为了尽最大可能避免内存泄露问题，建议这么写
//	        mTtsManager = TTSController.getInstance(getApplicationContext());
//	        mTtsManager.init();
//	        mTtsManager.startSpeaking();
//			
//	        //为了尽最大可能避免内存泄露问题，建议这么写
//	        mAMapNavi = AMapNavi.getInstance(getApplicationContext());
//	        mAMapNavi.setAMapNaviListener(this);
//	        mAMapNavi.setAMapNaviListener(mTtsManager);
//	        mAMapNavi.setEmulatorNaviSpeed(150);
//	        
//	        GetLocation01();
			
		}
	}
	
	 private void GetLocation01() {
			mlocationClient = new AMapLocationClient(this);
			// 初始化定位参数
			mLocationOption = new AMapLocationClientOption();
			// 设置定位监听
			mlocationClient.setLocationListener(this);
			// 设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
			mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
			// 设置定位间隔,单位毫秒,默认为2000ms
			mLocationOption.setInterval(10000);
			
			// 设置定位参数
			mlocationClient.setLocationOption(mLocationOption);
			// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
			// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
			// 在定位结束后，在合适的生命周期调用onDestroy()方法
			// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
			// 启动定位
			mlocationClient.startLocation();
		}
	    
	 public void onLocationChanged(AMapLocation amapLocation) {
			if (amapLocation != null) {
				if (amapLocation.getErrorCode() == 0) {
					// 定位成功回调信息，设置相关消息
					// amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
					amapLocation.getLatitude();// 获取纬度
					amapLocation.getLongitude();// 获取经度
					amapLocation.getAccuracy();// 获取精度信息
					if (amapLocation.getLatitude()>0 && amapLocation.getLongitude()>0 ) {
						
//						mStartLatlng.setLatitude(amapLocation.getLatitude());//
//						mStartLatlng.setLongitude(amapLocation.getLongitude());
//						Toast.makeText(MyMapLocation.this, amapLocation.getLatitude()
//								+ "----"+amapLocation.getLongitude()
//								+ "", 1000).show();;
//						  mStartList.add(mStartLatlng);
//					        mEndList.add(mEndLatlng);
//					        
//						// 算路
//						mAMapNavi.calculateDriveRoute(mStartList, mEndList, null,
//								PathPlanningStrategy.DRIVING_DEFAULT);
						
					}
					
				} else {
					Toast.makeText(MyMapLocation.this, amapLocation.getErrorCode(),
							1000).show();
					
				}
			}
		}
	
	/**
	 * 如果使用无起点算路，请这样写
	 */
	private void noStartCalculate() {
		// 无起点算路须知：
		// AMapNavi在构造的时候，会startGPS，但是GPS启动需要一定时间
		// 在刚构造好AMapNavi类之后立刻进行无起点算路，会立刻返回false
		// 给人造成一种等待很久，依然没有算路成功 算路失败回调的错觉
		// 因此，建议，提前获得AMapNavi对象实例，并判断GPS是否准备就绪
//		if (mAMapNavi.isGpsReady())
//			mAMapNavi.calculateDriveRoute(mEndList, mWayPointList,
//					PathPlanningStrategy.DRIVING_DEFAULT);
	}

	
	  /**
     * 调用高德导航
    */
	public void aMap(MyMapLocation MyMapLocation){
    if (AMapUtil.isInstallByRead("com.autonavi.minimap")){
            AMapUtil.goToNaviActivity(this,"rrqs",null,endlat,endlng,"0","2");
    }
    }

	/*
	 * check the app is installed
	 */
	private boolean isAppInstalled(Context context, String packagename) {
		PackageInfo packageInfo;
		try {
			packageInfo = context.getPackageManager().getPackageInfo(
					packagename, 0);
		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}
		if (packageInfo == null) {
			   AlertDialog.Builder builder = new AlertDialog.Builder(this);  
	            builder.setMessage("您尚未安装高德地图app或app版本过低，点击确认下载？");  
	            builder.setTitle("提示");  
	            builder.setPositiveButton("确认", new OnClickListener() {  
	                @Override  
	                public void onClick(DialogInterface dialog, int which) {  
	                    dialog.dismiss();  
	        			Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");// id为包名
	        			Intent it = new Intent(Intent.ACTION_VIEW, uri);
	        			startActivity(it);
	        			   MyMapLocation.this.finish();
	                }  
	            });  
	  
	            builder.setNegativeButton("取消", new OnClickListener() {  
	                @Override  
	                public void onClick(DialogInterface dialog, int which) {  
	                    dialog.dismiss();  
	                    MyMapLocation.this.finish();
	                }  
	            });  
	  
	            builder.create().show();  

			return false;
		} else {
			// System.out.println("已经安装");
//			try {
//				openGaoDeMap();
				aMap(this);
				   MyMapLocation.this.finish();
//			} catch (URISyntaxException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			return true;
		}
	}

	@Override
	public void onCalculateRouteSuccess() {//naviFlag为NaviType.GPS表示真实导航，naviFlag为NaviType.EMULATOR表示模拟导航
//		mAMapNavi.startNavi(AMapNavi.GPSNaviMode);
	}
	

    @Override
    protected void onResume() {
        super.onResume();
//        mAMapNaviView.onResume();
       
    }

    @Override
    protected void onPause() {
        super.onPause();
//        mAMapNaviView.onPause();
//
////        仅仅是停止你当前在说的这句话，一会到新的路口还是会再说的
//        mTtsManager.stopSpeaking();
//
//        停止导航之后，会触及底层stop，然后就不会再有回调了，但是讯飞当前还是没有说完的半句话还是会说完
//        mAMapNavi.stopNavi();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mAMapNaviView.onDestroy();
        //since 1.6.0 不再在naviview destroy的时候自动执行AMapNavi.stopNavi();
        //请自行执行
//        mAMapNavi.stopNavi();
//        mAMapNavi.destroy();
//        mTtsManager.destroy();
    }

    @Override
    public void onInitNaviFailure() {
        Toast.makeText(this, "init navi Failed", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onInitNaviSuccess() {
//        mAMapNavi.calculateDriveRoute(mStartList, mEndList, mWayPointList, PathPlanningStrategy.DRIVING_DEFAULT);
    }

    @Override
    public void onStartNavi(int type) {

    }

    @Override
    public void onTrafficStatusUpdate() {

    }

    @Override
    public void onLocationChange(AMapNaviLocation location) {

    }

    @Override
    public void onGetNavigationText(int type, String text) {

    }

    @Override
    public void onEndEmulatorNavi() {
    }

    @Override
    public void onArriveDestination() {
    }

//    @Override
//    public void onCalculateRouteSuccess() {
//        mAMapNavi.startNavi(AMapNavi.EmulatorNaviMode);
//    }

    @Override
    public void onCalculateRouteFailure(int errorInfo) {
    }

    @Override
    public void onReCalculateRouteForYaw() {

    }

    @Override
    public void onReCalculateRouteForTrafficJam() {

    }

    @Override
    public void onArrivedWayPoint(int wayID) {

    }

    @Override
    public void onGpsOpenStatus(boolean enabled) {
    }

    @Override
    public void onNaviSetting() {
    }

    @Override
    public void onNaviMapMode(int isLock) {

    }

    @Override
    public void onNaviCancel() {
        finish();
    }


    @Override
    public void onNaviTurnClick() {

    }

    @Override
    public void onNextRoadClick() {

    }


    @Override
    public void onScanViewButtonClick() {
    }

    @Deprecated
    @Override
    public void onNaviInfoUpdated(AMapNaviInfo naviInfo) {
    }

    @Override
    public void onNaviInfoUpdate(NaviInfo naviinfo) {
    }

    @Override
    public void OnUpdateTrafficFacility(TrafficFacilityInfo trafficFacilityInfo) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {

    }

    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {
    }

    @Override
    public void hideCross() {
    }

    @Override
    public void showLaneInfo(AMapLaneInfo[] laneInfos, byte[] laneBackgroundInfo, byte[] laneRecommendedInfo) {

    }

    @Override
    public void hideLaneInfo() {

    }

    @Override
    public void onCalculateMultipleRoutesSuccess(int[] ints) {

    }


    @Override
    public void onLockMap(boolean isLock) {
    }

    @Override
    public boolean onNaviBackClick() {
        return false;
    }
	@Override
	public void onNaviViewLoaded() {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void notifyParallelRoad(int arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void updateAimlessModeStatistics(AimLessModeStat arg0) {
		// TODO Auto-generated method stub
		
	}

}
